package com.gzx.bi.modular.team.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.gzx.bi.modular.screen.entity.GzxHtCallReceiptBusiness;
import com.gzx.bi.modular.team.bo.GzxTeamEffectBo;
import com.gzx.bi.modular.team.entity.GzxTeamEffect;
import com.gzx.bi.modular.team.mapper.GzxTeamEffectMapper;
import com.gzx.bi.modular.team.service.GzxTeamEffectService;
import com.gzx.bi.modular.team.vo.GzxTeamEffectVo;
import com.gzx.bi.modular.user.service.GzxUserDebtService;
import com.gzx.bi.modular.user.vo.GzxUserDebtVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 团队效率
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GzxTeamEffectServiceImpl implements GzxTeamEffectService {

    private final GzxTeamEffectMapper gzxTeamEffectMapper;

    private final GzxUserDebtService gzxUserDebtService;

    /**
     * 获取团队效率报表
     */
    @DS("bi")
    @Override
    public List<GzxTeamEffectVo> getTeamEffect(GzxTeamEffectBo bo) {
        if(ObjectUtil.isNotEmpty(bo.getBelongProject())){
            bo.setBelongProject("('" + bo.getBelongProject().replaceAll(",", "','") + "')");
        }
        //计算团队效率，数据不多（一天几百上千条）直接sql算
        List<GzxTeamEffectVo> list = gzxTeamEffectMapper.getTeamEffect(bo);
        if (!list.isEmpty()) {
            //计算合计列 ，生成一行合计数据放到list最后一条
            GzxTeamEffectVo total = new GzxTeamEffectVo();
            total.setAttendUser(list.stream().mapToInt(GzxTeamEffectVo::getAttendUser).sum());
            total.setDebtUser(list.stream().mapToInt(GzxTeamEffectVo::getDebtUser).sum());
            total.setCaseLoad(list.stream().mapToInt(GzxTeamEffectVo::getCaseLoad).sum());
            total.setAvgCase(list.stream().mapToInt(GzxTeamEffectVo::getAvgCase).sum() / list.size());
            total.setCalloutNum(list.stream().mapToInt(GzxTeamEffectVo::getCalloutNum).sum());
            total.setConnectNum(list.stream().mapToInt(GzxTeamEffectVo::getConnectNum).sum());
            total.setConnectDuration(list.stream().mapToInt(GzxTeamEffectVo::getConnectDuration).sum());
            total.setEffectDuration(list.stream().mapToInt(GzxTeamEffectVo::getEffectDuration).sum());
            total.setAvgCallout(list.stream().mapToDouble(GzxTeamEffectVo::getAvgCallout).sum() / list.size());
            total.setAvgConnectDuration(list.stream().mapToDouble(GzxTeamEffectVo::getAvgConnectDuration).sum() / list.size());
            total.setAvgEffectDuration(list.stream().mapToDouble(GzxTeamEffectVo::getAvgEffectDuration).sum() / list.size());
            total.setRateConnect(list.stream().mapToDouble(GzxTeamEffectVo::getRateConnect).sum() / list.size());
            total.setRateActive(list.stream().mapToDouble(GzxTeamEffectVo::getRateActive).sum() / list.size());
            total.setRateAvgActive(list.stream().mapToDouble(GzxTeamEffectVo::getRateAvgActive).sum() / list.size());
            list.add(total);
        }
        return list;
    }

    /**
     * 团队效率报表
     */
    @DS("bi")
    @Override
    public void saveTeamBatch(List<ConsumerRecord<String, String>> recordList) {
        //把话单转成对象
        List<GzxHtCallReceiptBusiness> list = recordList.stream().map(rowData -> JSON.parseObject(rowData.value(), GzxHtCallReceiptBusiness.class)).toList();
        log.info("从MQ中批量获取话单：本批次处理event数量{}", list.size());

        //获取坐席的所属项目，小组
        List<GzxUserDebtVo> userDebtList = gzxUserDebtService.getUserDebt(list);
        log.info("获取坐席的所属项目，小组：{}", userDebtList.size());

        //保存报表数据
        list.forEach(record -> {
            //批量入库不好计算，每条数据都要重新计算数量，构建team对象
            GzxTeamEffect team = new GzxTeamEffect();
            // 从userDebtList中筛选出account等于team.agentNum的对象
            List<GzxUserDebtVo> userDebtVos = userDebtList.stream()
                    .filter(userDebt -> userDebt != null && userDebt.getAccount() != null && userDebt.getAccount().equals(record.getAgentNum()))
                    .toList();
            GzxUserDebtVo userDebtVo = new GzxUserDebtVo();
            if (!userDebtVos.isEmpty()) {
                userDebtVo = userDebtVos.getFirst();
            }
            if (ObjectUtil.isNotEmpty(userDebtVo.getBelongProject())) {
                team.setBelongTeam(userDebtVo.getBelongTeam());
                team.setBelongProject(userDebtVo.getBelongProject());
            } else {
                //关联不到项目的坐席，跳过，个人中心那里一定要配置所属项目
                return;
            }

            //封装team对象
            team.setAgentNum(record.getAgentNum());
            //外呼总量，calloutNum直接+1
            int calloutNum = 0;
            if (0 != record.getCallType()) {
                calloutNum = 1;
            }
            //接通总量
            int connectNum = 0;
            //有效通话时长
            int effectDuration = 0;

            int duration = record.getCallDuration();
            if (duration > 0) {
                connectNum = 1;
            }
            if (duration > 10) {
                effectDuration = duration;
            }
            team.setCalloutNum(calloutNum);
            team.setConnectNum(connectNum);
            team.setConnectDuration(duration);
            team.setEffectDuration(effectDuration);

            //入库
            gzxTeamEffectMapper.insertUpdate(team);
        });
    }
}
